'use client'

import { useMemo } from "react"

import { ChatSession } from "@prisma/client"
import ChatSessionItem from './chat-session-item'
import { useAppContextSelector } from "@/context/app-context"

const groupByDate = (chatList: ChatSession[]) => {
    const groupMap = new Map<string, ChatSession[]>()
    chatList.forEach((item) => {
        const now = new Date()
        const updateTime = new Date(item.updatedAt)
        let key = "未知时间"
        const dayDiff = Math.floor(
            (now.getTime() - updateTime.getTime()) / (1000 * 60 * 60 * 24)
        )
        if (dayDiff === 0 && now.getDate() === updateTime.getDate()) {
            key = "今天"
        } else if (dayDiff <= 7) {
            key = "最近7天"
        } else if (dayDiff <= 31) {
            key = "最近一个月"
        } else if (now.getFullYear() === updateTime.getFullYear()) {
            key = `${updateTime.getMonth() + 1}月`
        } else {
            key = `${updateTime.getFullYear()}`
        }
        if (groupMap.has(key)) {
            groupMap.get(key)?.push(item)
        } else {
            groupMap.set(key, [item])
        }
    })
    groupMap.forEach((item) => {
        item.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())
    })
    const groupList = Array.from(groupMap).sort(([, list1], [, list2]) => {
        return (list2[list2.length - 1].updatedAt.getTime() - list1[list1.length - 1].updatedAt.getTime())
    })
    return groupList
}

const ChatSessionList = () => {
    const chatSessions = useAppContextSelector(state => state.chatSessions)
    const [selectedChat, setSelectedChat] = useAppContextSelector(state => [state.currentChatSession, state.setCurrentChatSession])

    const groupList = useMemo(() => {
        return groupByDate(chatSessions)
    }, [chatSessions])

    return (
        <div className='flex-1 mb-[48px] mt-2 flex flex-col overflow-y-auto'>
            {groupList.map(([date, list]) => {
                return (
                    <div key={date}>
                        <div className='sticky top-0 z-10 p-3 text-sm bg-gray-900 text-gray-500'>
                            {date}
                        </div>
                        <ul>
                            {list.map((item) => {
                                const selected = selectedChat?.id === item.id
                                return (
                                    <ChatSessionItem
                                        key={item.id}
                                        item={item}
                                        selected={selected}
                                        onSelected={setSelectedChat}
                                    />
                                )
                            })}
                        </ul>
                    </div>
                )
            })}
        </div>
    )
}

export default ChatSessionList
